/**
 * Author:
 * Time: 2016/7/6 0006
 */
angular.module('md.home', [

    ])

    .config(['$stateProvider',   '$urlRouterProvider',
        function($stateProvider, $urlRouterProvider) {
            $stateProvider

            .state('home', {
                url : '/home',
                templateUrl : 'view/home.html',
                controller : 'HomeController'
            })

        }])

    .controller('HomeController', ['$scope', '$state','testService', function($scope,$state,testService) {
        console.log("map start");
        //地图容器
        $scope.address = "";//搜索地址
        $scope.i = 0;//用来做显示与影藏
        $scope.scopeArr = [];//区域数组
        var mapObj = new AMap.Map('iCenter',{
            resizeEnable: true,//是否监控地图容器尺寸变化，默认值为false
            zoom:11,//缩放级别
        });
        //添加比例尺插件
        mapObj.plugin(["AMap.Scale"],function(){
            var scale = new AMap.Scale();
            mapObj.addControl(scale);
        });
        //IP定位
        //加载IP定位插件
        mapObj.plugin(["AMap.CitySearch"], function() {
            //实例化城市查询类
            var citysearch = new AMap.CitySearch();
            //自动获取用户IP，返回当前城市
            citysearch.getLocalCity();
            AMap.event.addListener(citysearch, "complete", function(result){
                if(result && result.city && result.bounds) {
                    $scope.city = result.city;
                    document.getElementById('city').innerHTML = ""+$scope.city+"";
                }
                else {
                    $scope.city = result.info;
                    document.getElementById('city').innerHTML = ""+$scope.city+"";
                }
            });
            AMap.event.addListener(citysearch, "error", function(result){alert(result.info);});
        });
        //输入提示
        $scope.autoSearch = function(){
            var auto;
            mapObj.plugin(["AMap.Autocomplete"], function() {
                auto = new AMap.Autocomplete({
                    pageIndex: 1,
                    pageSize: 10,
                    city: $scope.city //城市，默认全国
                });
            });
            //查询成功时返回查询结果
            AMap.event.addListener(auto, "complete", autocomplete_CallBack);
            if(!$scope.address){
                document.getElementById("result1").style.display = "none";
            }else{
                auto.search($scope.address);
            }
        }
        //地址搜索
        $scope.searchAddress = function(){
            mapObj.clearMap();
            mapObj.plugin(["AMap.PlaceSearch"], function() {
                var msearch = new AMap.PlaceSearch();  //构造地点查询类
                AMap.event.addListener(msearch, "complete", function(data){
                    var resultStr = "";
                    console.log(data);
                    var poiArr = data.poiList.pois;
                    var resultCount = poiArr.length;
                    for (var i = 0; i < resultCount; i++) {
                        $scope.addmarker(i, poiArr[i]);
                    }
                    mapObj.setFitView();
                }); //查询成功时的回调函数
                $scope.address = document.getElementById("searchKeywords").value;
                msearch.search($scope.city+$scope.address);  //关键字查询查询
            });
        }

        $scope.addmarker = function(i, d){
            var lngX;
            var latY;
            var iName;
            var iAddress;
            if(d.location){
                lngX = d.location.getLng();
                latY = d.location.getLat();
            }else{
                lngX = d._location.getLng();
                latY = d._location.getLat();
            }
            if(d.name){
                iName = d.name;
            }else{
                iName = d._name;
            }
            if(d.name){
                iAddress = d.address;
            }else{
                iAddress = d._address;
            }
            var markerOption = {
                map:mapObj,
                icon:"http://webapi.amap.com/images/" + (i + 1) + ".png",
                position:new AMap.LngLat(lngX, latY)
            };
            var mar = new AMap.Marker(markerOption);
            mar.getPosition();

            var infoWindow = new AMap.InfoWindow({
                content:"<h3><font color=\"#00a6ac\">" + (i + 1) + ". " + iName + "</font></h3>",
                size:new AMap.Size(300, 0),
                autoMove:true,
                offset:new AMap.Pixel(0,-30)
            });
            var aa = function (e) {infoWindow.open(mapObj, mar.getPosition());};
            AMap.event.addListener(mar, "click", aa);
        }
        //添加点击地图事件
        $scope.area_Select = function(){
            $scope.scope_kilometer= "";
            mapObj.setDefaultCursor("crosshair");
            mapObj.on('click', $scope._onclick);
        }
        //获取经纬度
        var lng;
        var lat;
        $scope._onclick = function (e) {
            $scope.i = 1;
            $("#choose").show();
            $("#area_Select").hide();
            lng = e.lnglat.getLng();
            lat = e.lnglat.getLat();
            var prompt = '经度：'+ lng +'纬度：'+ lat;
            new AMap.Marker({
                position: e.lnglat,
                map: mapObj
            });
            $('#myModal1').modal('show');
        }
        //弹出输入配送距离范围
        $scope.modal_sure1 = function () {
            console.log($scope.scope_kilometer);
            if($scope.scope_kilometer!= ""){
                $('#myModal1').modal('hide');
                $scope.getPosition(lng,lat,$scope.scope_kilometer);//画区域
            }else{
                alert("请输入大致配送距离")
            }
        }
        //提交所在区域
        $scope.add_area = function(){
            alert("确定选择该区域？");
            alert($scope.scopeArr);
            $("#area_Select").show();
            $("#choose").hide();
        }
        //取消触发时间
        $scope.cancel = function(){
            mapObj.clearMap();
            mapObj.off('click',$scope._onclick);
            mapObj.setDefaultCursor("pointer");
            $("#area_Select").show();
            $("#choose").hide();
        }
        //自动生成商家位置区域范围1km=0.01
        $scope.getPosition = function(Longitude,Latitude,scope_data){
            var data = scope_data/100;
            pointer = [
                [Longitude-data,Latitude-data],
                [Longitude+data,Latitude-data],
                [Longitude+data,Latitude+data],
                [Longitude-data,Latitude+data],
            ];
            $scope.painting(pointer);
        }
        //绘制多边形
        var _polygon;
        var polygonEditor;
        $scope.painting = function(arr){
            console.log(arr)
            mapObj.setDefaultCursor("pointer");
            mapObj.off('click', $scope._onclick);
            _polygon = new AMap.Polygon({
                map: mapObj,
                path: arr,
                strokeColor: "#FF0000",
                strokeOpacity: 1,
                strokeWeight: 1,
                fillColor: "#f5deb3",
                fillOpacity: 0.5
            });
            //加载编辑插件
            mapObj.plugin(["AMap.PolyEditor"],function(){
                polygonEditor = new AMap.PolyEditor(mapObj, _polygon);
            });
        }
        //编辑多边形
        $scope.startEditPolygon=function(){
            polygonEditor.open();
        }
        $scope.closeEditPolygon=function(){
            $scope.scope_fee="";
            $('#myModal').modal('show');
        }
        //输入配送费
        $scope.modal_sure=function(){
            polygonEditor.close();
            mapObj.clearMap();
            $("#area_Select").show();
            $("#choose").hide();
            $('#myModal').modal('hide');
            $scope.set_point();
        }
        //坐标分装
        var point_coord = [];
        $scope.coord_fee_arr = [];
        $scope.set_point = function(){
            var point_coord = [];
            var point_arr = _polygon.getPath();
            console.log(point_arr.length);
            for(var i=0;i<point_arr.length;i++){
                point_coord.push({
                    "lng" : point_arr[i].lng,
                    "lat" : point_arr[i].lat
                });
            }
            console.log(point_coord);
            $scope.coord_fee_arr.push({
                "coord_arr" : point_coord,
                "fee" : $scope.scope_fee
            })
        }



    }])